//
//  CreateRecordViewController.m
//  mark
//
//  Created by student5 on 2021/12/13.
//

#import <Foundation/Foundation.h>
#import "CreateRecordViewController.h"

@interface CreateRecordViewController ()

@property UIButton *backButton;
@property(nonatomic,strong)UIButton *applyButton;  //应用按钮
@property(nonatomic,strong)UIDatePicker *datePicker;
//@property(nonatomic,strong)UITextField *timeTextField;
@property(nonatomic,strong)UITextView *urlTextField;     //url输入框
@property(nonatomic,strong)UITextView *summaryTextField; //简介
@property(nonatomic,strong)UILabel *timeLabel;  //label设置提醒时间
@property(nonatomic,strong)UILabel *urlLabel;  //提示输入url
@property(nonatomic,strong)UILabel *summaryLabel;  //简介
@property(nonatomic,strong)UINavigationBar *navigationBar;
@property (strong,nonatomic) NSArray *paths;
@property (strong,nonatomic) NSString *diskCachePath;//记录cache位置

@end

#define SCREEN_WIDTH ([[UIScreen mainScreen] bounds].size.width)
#define SCREEN_HEIGHT ([[UIScreen mainScreen] bounds].size.height) //宏

@implementation CreateRecordViewController

-(void)viewDidLoad{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self setNavigationbar];//设置导航栏
    [self backbtn];
    [self setupDateKeyPan];//设置提醒时间
    [self set_urlTextFeild];//获取url
    [self set_summaryTextFeild];//获取url
    [self applybtn];//应用按钮


    self.paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    self.diskCachePath = [[self.paths objectAtIndex:0] stringByAppendingPathComponent:@"dataCache"];//获取cache位置
}

- (void)backbtn{  //返回主界面
    self.backButton = [[UIButton alloc]initWithFrame:CGRectMake(20, 28, 50, 30)];
    [self.backButton setTitle:@"返回"forState:UIControlStateNormal];
    //返回按钮的边框以后再具体设置
    self.backButton.layer.cornerRadius = 5;
    self.backButton.layer.borderWidth = 1;
    self.backButton.layer.borderColor = [UIColor grayColor].CGColor;
    [self.backButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.backButton addTarget:self action:@selector(backButtonPressed:) forControlEvents:UIControlEventTouchUpInside];//添加事件
    
    [self.view addSubview:self.backButton];

}




-(void)backButtonPressed:(id)sender{ //返回按钮点击
    NSLog(@"backButtonPressed");
    //跳转到起始页面
    [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}



- (void)set_urlTextFeild {
    //提示输入url label
    CGRect rect = CGRectMake(40, 100, 200, 50);
    UILabel *urllabel = [[UILabel alloc] initWithFrame:rect];
    urllabel.text = @"输入网页对应的url："; //设置内容
    self.urlLabel = urllabel;
    
    UITextView *TextField = [[UITextView alloc]initWithFrame:CGRectMake(50, 150, SCREEN_WIDTH-100, 40)];
    //设置边框
    TextField.delegate = self;
    TextField.textContainer.maximumNumberOfLines = 0;
    TextField.autocorrectionType = UITextAutocorrectionTypeNo;//取消自动纠错
    TextField.autocapitalizationType = UITextAutocapitalizationTypeNone;//取消首字母大写
    TextField.layer.borderWidth =1.0;
    TextField.layer.cornerRadius =5.0;
    TextField.layer.borderColor = [UIColor grayColor].CGColor;
    //设置字体样式和大小
    TextField.font = [UIFont fontWithName:@"Arial" size:20.0f];
    //对齐方式为左对齐
    TextField.textAlignment = UITextAlignmentLeft;
    
    self.urlTextField = TextField;
    
    [self.view addSubview:self.urlLabel];
    [self.view addSubview:self.urlTextField];
}


- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]) {
        return NO;
    }
    return YES;
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
  return YES;
}


- (void)setupDateKeyPan {
    //因为datapicker
    UIDatePicker *datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(50, 260, 150, 40)];
    
    //设置地区: zh-中国
    datePicker.locale = [NSLocale localeWithLocaleIdentifier:@"zh"];
    
    //设置日期模式(Displays month, day, and year depending on the locale setting)
    datePicker.datePickerMode = UIDatePickerModeDateAndTime;
    // 设置当前显示时间
    [datePicker setDate:[NSDate date] animated:YES];
    
    self.datePicker = datePicker;
    
    //年月日label
    CGRect rect = CGRectMake(40, 210, 200, 50);
    UILabel *timelabel = [[UILabel alloc] initWithFrame:rect];
    timelabel.text = @"设置提醒时间："; //设置内容
    self.timeLabel = timelabel;

    [self.view addSubview:self.timeLabel];
    [self.view addSubview:self.datePicker];
}




- (void)set_summaryTextFeild {
    //提示输入简介 label
    CGRect rect = CGRectMake(40, 310, 200, 50);
    self.summaryLabel = [[UILabel alloc] initWithFrame:rect];
    self.summaryLabel.text = @"简介："; //设置内容
    
    UITextView *TextField = [[UITextView alloc]initWithFrame:CGRectMake(50, 360, SCREEN_WIDTH-100, 100)];
    //设置边框
    TextField.layer.borderColor = [UIColor grayColor].CGColor;
    TextField.layer.borderWidth =1.0;
    TextField.layer.cornerRadius =5.0;
    //滑动条
    TextField.scrollEnabled = YES;
    
    TextField.autocorrectionType = UITextAutocorrectionTypeNo;//取消自动纠错
    TextField.autocapitalizationType = UITextAutocapitalizationTypeNone;//取消首字母大写
    
    //有关于键盘的问题好像还没有解决
    
    //TextField.autoresizingMask = UIViewAutoresizingFlexibleHeight;//自适
    //设置字体样式和大小
    TextField.font = [UIFont fontWithName:@"Arial" size:15.0f];
    //对齐方式为居中
    TextField.textAlignment = UITextAlignmentLeft;
    TextField.keyboardType = UIKeyboardTypePhonePad;
    self.summaryTextField = TextField;
    
    [self.view addSubview:self.summaryLabel];
    [self.view addSubview:self.summaryTextField];
}




- (void)applybtn{  //创建
    self.applyButton = [[UIButton alloc]initWithFrame:CGRectMake(120, 500, SCREEN_WIDTH-240, 40)];
    [self.applyButton setTitle:@"创建"forState:UIControlStateNormal];

    [self.applyButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.applyButton addTarget:self action:@selector(applyButtonPressed:) forControlEvents:UIControlEventTouchUpInside];//添加事件
    self.applyButton.layer.borderColor = [UIColor grayColor].CGColor;
    self.applyButton.layer.borderWidth = 1.0f;
    self.applyButton.layer.cornerRadius = 5.0f;
    [self.view addSubview:self.applyButton];
}




-(void)applyButtonPressed:(id)sender{ //应用按钮点击
    NSLog(@"applyButtonPressed");
    //
    NSString *urlString = self.urlTextField.text;//获取url输入中的文字
    //NSLog(urlString);
    NSString *summaryString = self.summaryTextField.text;//获取summary输入框中文字
    //NSLog(summaryString);
    NSString *dateString = [self getdate:self.datePicker];
   //NSLog(dateString);
    
    //把三个变量都存起来，未实现
    [self saveData];
    //跳转到起始页面
    //[self.father_view reloadTableViewData];//刷新主页面中的tableview
    [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}



-(void)saveData{//保存数据到本地
    NSString *urlString = self.urlTextField.text;
    NSString *summaryString = self.summaryTextField.text;
    NSString *dateString = [self getdate:self.datePicker];
    NSString *fontString = @"100";
    int i = 0;
    NSMutableArray *send_array;//
    
    send_array = [[NSMutableArray alloc] init];
    
    NSString *url_help_search_string;//辅助搜索用字符串
    NSString *summary_help_search_string;
    NSString *date_help_search_string;
    NSString *html_help_search_string;
    NSString *font_help_search_string; //字体大小
    
    // 获得新的沙盒路径
    NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [directoryPaths objectAtIndex:0];
    
    summary_help_search_string = [NSString stringWithFormat:@"summary%d.txt",i];
    date_help_search_string = [NSString stringWithFormat:@"date%d.txt",i];
    url_help_search_string = [NSString stringWithFormat:@"url%d.txt",i];
    html_help_search_string = [NSString stringWithFormat:@"html%d",i];
    font_help_search_string = [NSString stringWithFormat:@"font%d",i];
    
    
    url_help_search_string = [documentDirectory stringByAppendingPathComponent:url_help_search_string];
    summary_help_search_string = [documentDirectory stringByAppendingPathComponent:summary_help_search_string];
    date_help_search_string = [documentDirectory stringByAppendingPathComponent:date_help_search_string];
    html_help_search_string = [documentDirectory stringByAppendingPathComponent:html_help_search_string];
    font_help_search_string = [documentDirectory stringByAppendingPathComponent:font_help_search_string];
    
    while([[NSFileManager defaultManager]fileExistsAtPath:url_help_search_string]){//不存在则跳出，保证文件名按顺序
        i++;
        NSLog(@"save at %d",i);
        summary_help_search_string = [NSString stringWithFormat:@"summary%d.txt",i];
        date_help_search_string = [NSString stringWithFormat:@"date%d.txt",i];
        url_help_search_string = [NSString stringWithFormat:@"url%d.txt",i];
        html_help_search_string = [NSString stringWithFormat:@"html%d.",i];
        font_help_search_string = [NSString stringWithFormat:@"font%d.txt",i];
        
        url_help_search_string = [documentDirectory stringByAppendingPathComponent:url_help_search_string];
        summary_help_search_string = [documentDirectory stringByAppendingPathComponent:summary_help_search_string];
        date_help_search_string = [documentDirectory stringByAppendingPathComponent:date_help_search_string];
        html_help_search_string = [documentDirectory stringByAppendingPathComponent:html_help_search_string];
        font_help_search_string = [documentDirectory stringByAppendingPathComponent:font_help_search_string];
        
        
    }
    NSError *error;
    //下面代码的顺序不要调换，可能导致输出不正确
    
    //NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:summary_help_search_string];
    [summaryString writeToFile:summary_help_search_string atomically:YES encoding:NSUTF8StringEncoding error:&error];//存储summary
    [send_array addObject:summary_help_search_string];
    
    [dateString writeToFile:date_help_search_string atomically:YES encoding:NSUTF8StringEncoding error:&error];//存储date
    [send_array addObject:date_help_search_string];
    
    //filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:url_help_search_string];
    [urlString writeToFile:url_help_search_string atomically:YES encoding:NSUTF8StringEncoding error:&error];//存储url
    [send_array addObject:url_help_search_string];
    
    //存储html文件
    NSURL *real_url = [NSURL URLWithString:urlString];//string转化为url
    NSString *html_string = [NSString stringWithContentsOfURL:real_url encoding:NSUTF8StringEncoding error:nil];
    [html_string writeToFile:html_help_search_string atomically:YES encoding:NSUTF8StringEncoding error:nil];
    if([[NSFileManager defaultManager] fileExistsAtPath:html_help_search_string]){
        NSLog(@"save html success");
    }
    [send_array addObject:html_help_search_string];  //[3]
    
    [fontString writeToFile:font_help_search_string atomically:YES encoding:NSUTF8StringEncoding error:&error];//存储字体大小，初始为100
    [send_array addObject:font_help_search_string];  //[4]
    
    
    [self send_notification:self.datePicker.date index:url_help_search_string];
    [self.father_view sort_time];//在刷新之前给记录按时间排序
    [self.father_view addData:send_array];  //这里顺带着刷新了主页面的UItableview
}



//获取设置好的时间
- (NSString*)getdate:(UIDatePicker *)datePicker {
    //从datepicker中获取时间NSDate类型
    NSLog(@"getdate");
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    //设置时间格式
    formatter.dateFormat = @"yyyy-MM-dd hh:mm a";
    NSString *dateStr = [formatter  stringFromDate:datePicker.date];
    
    return dateStr;
}



//导航栏
-(void)setNavigationbar{
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    UINavigationBar *navigationBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 20, screenRect.size.width, 80.0f)];
    
    //创建UINavigationItem
    UINavigationItem *navigationBarTitle = [[UINavigationItem alloc] initWithTitle:@"创建"];
    NSDictionary *attrs = @{NSFontAttributeName : [UIFont systemFontOfSize:20]};
    [navigationBar setTitleTextAttributes:attrs];
    [navigationBar pushNavigationItem:navigationBarTitle animated:YES];
    [self.view addSubview: navigationBar];
}



//设置新的notification，传入参数是url的存储路径
-(void)send_notification:(NSDate *)date index:(NSString *)index_string{
    // 授权通知
    UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:setting];

    //创建通知，在app运行时不会弹出，回到主界面
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    if (nil != notification){
        NSLog(@"send notification!");
        NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init];
        dateFormatter.dateFormat = @"yyyy-MM-dd hh:mm a";
        //设置通知弹出的时间
        notification.fireDate = date;
        //设置重复重复间隔为每天
        notification.repeatInterval = kCFCalendarUnitDay;
        // 设置时区
        notification.timeZone= [NSTimeZone defaultTimeZone];
        //设置提示消息
        notification.alertBody = [NSString stringWithFormat:@"%@",@"你有未看的记录"];
        
        //消掉 icon 上 红色数字
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
        //取消推送用的字典便于识别 forkey:@"key" nsstring 存储地址对应的那个数字
        //NSString *index_string = [NSString stringWithFormat:@"%d",index];
        NSDictionary * Dic = [NSDictionary dictionaryWithObject:index_string forKey:@"key"];
        notification.userInfo = Dic;
        // 启动通知
        [[UIApplication sharedApplication]scheduleLocalNotification:notification];
    }
}





@end
